<template>
  <view>
    <div class="camera-box">
      <!-- 这里是显示的画面 -->
      <div class="show-box">
        <video
          v-show="videoState"
          id="video"
        />
        <canvas
          v-show="!videoState"
          id="canvas"
        />
      </div>

      <!-- 按钮功能区 -->
      <div class="iCenter">
        <el-button
          v-if="!videoState"
          class="startPhoto-button"
          type="primary"
          size="small"
          @click="videoState = !videoState"
        >
          开启摄像头
        </el-button>
        <el-button
          v-if="videoState"
          class="startPhoto-button"
          type="primary"
          size="small"
          @click="videoState = !videoState"
        >
          关闭摄像头
        </el-button>
      </div>
   <!--   <div style="display: flex;justify-content: center;align-items: center; width: 100%;">
        <img v-if="result" :src="result" style="height: 100px;width: 100px;" alt="识别图"/>
      </div> -->

      <div class="photo-history-box">
        <!-- 上传图片 -->
        <div style="display:flex;align-items:center;justify-content:end;">
          <div>
            <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              action="http://localhost:8086/Img/detect"
              :on-success="handleSuccess"
              :on-progress="handleProgress"
              accept="image/png,image/jpeg,image/jpg"
              style="margin-bottom: -15px;"
            >
              <el-icon size="30">
                <i-ep-PictureRounded />
              </el-icon>
            </el-upload>
            <div style="text-align: center">
              <p style="font-size: 12px">
                相 册
              </p>
            </div>
          </div>
        </div>
        <div
          style="border-radius: 20px;border:solid 1px black"
          class="take-phone-box"
          @click="takePhone"
        >
          <div style="border-radius: 20px;background-color: #ffa411;width:50px;height:50px;margin: 1px 1px" />
        </div>
        <div style="display:flex;align-items:center;justify-content:end;">
          <div>
            <el-icon
              size="30"
            >
              <i-ep-Clock />
            </el-icon>
            <div
              style="text-align: center;margin-top: -5px"
              @click="toPhotoHistoryPage"
            >
              <p style="font-size: 12px">
                历 史
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-drawer
      v-model="drawer"
      title="I am the title"
      :direction="direction"
      :with-header="false"
      :size="size"
    >
      <p>识别结果</p>
      <div id="detect-box">
        <span />
      </div>
    </el-drawer>
  </view>
</template>

<script setup>
import { View } from '@element-plus/icons-vue'
import axios from 'axios'

const blobFile = ref(null)
const canvas = ref(null)
const video = ref(null)
const videoState = ref(false)
const mediaStreamTrack = ref()
const result = ref("")
const drawer = ref(false)
const direction = ref('btt')
const size = ref('80%')
const isDetect = ref(false)

onMounted(() => {
  // 摄像头
  video.value = document.getElementById('video')
  // 画布
  canvas.value = document.getElementById('canvas').childNodes[0]
})
watch(videoState, (newValue, oldValue) => {
  if (newValue) {
    let video = document.querySelector('video')
    // 兼容代码
    window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL
    if (navigator.mediaDevices === undefined) {
      navigator.mediaDevices = {}
    }
    if (navigator.mediaDevices.getUserMedia === undefined) {
      navigator.mediaDevices.getUserMedia = function (constraints) {
        const getUserMedia =
          navigator.webkitGetUserMedia ||
          navigator.mozGetUserMedia ||
          navigator.msGetUserMedia
        if (!getUserMedia) {
          return Promise.reject(
            new Error('getUserMedia is not implemented in this browser')
          )
        }
        return new Promise(function (resolve, reject) {
          getUserMedia.call(navigator, constraints, resolve, reject)
        })
      }
    }
    const mediaOpts = {
      audio: false,
      video: true,
      video: { facingMode: 'user' } // 或者 "environment"
      // video: { width: 1280, height: 720 }
      // video: { facingMode: { exact: "environment" } }// 或者 "user"
    }
    navigator.mediaDevices
      .getUserMedia(mediaOpts)
      .then(function (stream) {
        mediaStreamTrack.value = stream
        video = document.querySelector('video')
        if ('srcObject' in video) {
          video.srcObject = stream
        } else {
          video.src =
            (window.URL && window.URL.createObjectURL(stream)) || stream
        }
        video.play()
      })
      .catch(function (err) {
        console.log(err)
      })
  }
})
// base64转file方式附上
const dataURLtoFile = (dataurl, filename) => {
  const arr = dataurl.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, { type: mime })
}
const requestLoad = (uploadFile) => {
  // 向后端发送识别请求API...
  // console.log(uploadFile)
  const formData = new FormData()
  formData.append('file', uploadFile)
  console.log(window.localStorage.userId)
  axios.post(`http://localhost:8086/Img/detect/${window.localStorage.userId}`, formData)
    .then(function (response) {
      ElMessage.success('上传成功')
      drawer.value = true
      if (document.getElementById('detect-img')) {
        document.getElementById('detect-img').remove()
        document.getElementById('detect-name').remove()
      }
      const container = document.getElementById('detect-box')
      const img = document.createElement('img')
      img.src = "data:image/png;base64,"+response.data.data
      img.alt = '加载失败'
      img.className = 'detect-img'
      img.id = 'detect-img'
      img.style.width = '330px'
      img.style.height = '400px'
      img.style.backgroundColor = 'white'
      img.onclick = function () {
        gotoDetectResult(response.data.name) // 商品id
      }
      const p = document.createElement('p')
      p.id = 'detect-name'
      p.textContent = response.data.name
      container.appendChild(p)
      container.appendChild(img)
    })
    .catch(function () {
      ElMessage.error('上传失败，请重试')
    })
}

const gotoDetectResult = (name) => {
  uni.navigateTo({
    url: '/pages/search-prod-show/search-prod-show?prodName=' + name
  })
}

const takePhone = () => {
  // 点击拍照截图画面
  canvas.value.getContext('2d').drawImage(document.getElementById('video').childNodes[0].childNodes[0], 0, 100, 365, 300)
  const dataurl = canvas.value.toDataURL('image/jpeg')
  console.log(dataurl)
  blobFile.value = dataURLtoFile(dataurl, 'camera.jpg') // 储存响应的图片File
  // tips 此时已经获取到了File类型的数据 可直接向后端传递数据
  // 若需要formData类型的数据,需加上以下代码
  // 创建虚拟表单保存file
  const formData = new FormData()
  formData.append('file', blobFile.value) // 图片内容
  // tips 此时已经获取到了fromData类型的数据
  // console.log(formData.getAll('file'), 123) // 查看数据内容

  videoState.value = false // 关闭video
  // 向后端发送识别请求API...
  requestLoad(blobFile.value)
}
const toPhotoHistoryPage = () => {
  uni.navigateTo({
    url: '/pages/photoHistory-page/photoHistory-page'
  })
}
const handleSuccess = (response) =>{
  console.log(response.image)
  result.value = "data:image/png;base64,"+response.image;
}
const handleProgress = (evt, uploadFile) => {
  videoState.value = false
  const image = new Image()
  image.src = URL.createObjectURL(uploadFile.raw)
  console.log(image.src)
  image.onload = function (event) {
    URL.revokeObjectURL(this.src)
    canvas.value.getContext('2d').drawImage(image, 0, 100, 365, 300)
  }
  videoState.value = false // 关闭video
  // 向后端发送识别请求API...
  requestLoad(uploadFile.raw)
}
</script>

<style scoped lang="scss">
@use './photoSearch-page.scss';
</style>
